package logic

import (
	"context"
	"fmt"
	"time"
	"vip-shop-hub/models/cache"
	"vip-shop-hub/models/mysql"
	"vip-shop-hub/viprpc/internal/svc"
	"vip-shop-hub/viprpc/viprpc"

	"github.com/zeromicro/go-zero/core/logx"
	"k8s.io/apimachinery/pkg/util/json"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *viprpc.ProductListRequest) (*viprpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("list_%d", in)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	var list []*viprpc.ProductList
	if result == "" {
		var err error
		list, err = mysql.List(mysql.DB, in)
		if err != nil {
			return nil, err
		}
		maeshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, maeshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &viprpc.ProductListResponse{
		List: list,
	}, nil
}
